package cn.com.bluemoon.daps.notice.infrastructure;

import cn.com.bluemoon.daps.notice.infrastructure.entity.DapSendMailRecord;
import cn.com.bluemoon.daps.notice.infrastructure.service.DapSendMailRecordService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Jarod.Kong
 * @date 2021/6/22 22:37
 */
@Component
@Slf4j
@EnableScheduling
@EnableAsync
@ConditionalOnProperty("daps.message.retry.enable")
public class SyncRetryNotice {
    @Autowired
    private DapSendMailRecordService recordService;

    @Value("${daps.message.retry.fixedRate}")
    private long fixedRate;

    /**
     * 信息，15分钟一次
     */
    @Scheduled(fixedRateString = "${daps.message.retry.fixedRate}", initialDelayString = "${daps.message.retry.initialDelay}")
    public void retryErrorMsg() {
        LambdaQueryWrapper<DapSendMailRecord> eq = recordService.bmLambdaQuery().eq(DapSendMailRecord::getSendStatus, false);
        List<DapSendMailRecord> errors = recordService.list(eq);
        for (DapSendMailRecord error : errors) {
            boolean send = recordService.send(error);
            if (send) {
                error.setSendStatus(true);
                recordService.updateById(error);
            }
            log.warn("每{}分钟尝试发送消息id={},status:{}", fixedRate / 1000 / 60, error.getId(), send);
        }
    }
}
